<template>
  <div>
    <WithDialog
      :visible.sync="dialogVisible"
      title="预约会议室"
      :close-on-click-modal="false"
      :confirm-btn-loading="loading"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <el-form
        ref="elFormRef"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="auto"
      >
        <el-form-item prop="reason" label="使用原因">
          <el-input v-model="form.reason" placeholder="请输入使用原因" />
        </el-form-item>

        <el-form-item prop="conference_room_id" label="会议室">
          <el-select
            v-model="form.conference_room_id"
            placeholder="请选择会议室"
            @change="handleRoomChange"
          >
            <el-option
              v-for="item in meetingRoomList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="time" label="会议时间">
          <TimeDatePicker
            v-model="form.time"
            is-real-time
            end="17:00"
            :date-picker-options="timePickerOptions"
            @change="handleTimeChange"
          />
        </el-form-item>

        <el-form-item prop="notes" label="使用备注">
          <el-input v-model="form.notes" placeholder="请输入备注信息" />
        </el-form-item>

        <el-form-item prop="users" label="参会人员">
          <el-button
            v-if="form.users.length <= 0"
            type="primary"
            size="medium"
            @click="handleOpenUserSelect"
          >
            点击添加
          </el-button>

          <div
            v-else
            class="selected-warp"
          >
            <div class="selected-header flex">
              <div class="selected-header__title base-font">
                已选择：{{ form.users.length }}人
              </div>

              <el-button
                type="primary"
                size="medium"
                @click="handleOpenUserSelect"
              >
                点击添加
              </el-button>
            </div>

            <div class="selected-list">
              <div
                v-for="(item, index) in selectedUserMap?.slice(0, 10)"
                :key="index"
                class="selected-list__item"
              >
                <template>
                  <el-avatar
                    v-if="item?.head_portrait"
                    shape="square"
                    :src="item?.head_portrait"
                    :size="38"
                    style="flex-shrink:0;"
                    fit="cover"
                  />

                  <div v-else class="avatar--text">
                    {{ item.username.charAt(0) }}
                  </div>
                </template>

                <div class="name">{{ item.username }}</div>

                <div class="el-icon-error icon" @click="handleRemove(item.id)" />
              </div>

              <div
                v-if="selectedUserMap.length > 10"
                class="selected-list__item pointer"
                @click="handleOpenUserSelect"
              >
                <span>查看更多</span>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </WithDialog>

    <UserSelectModal
      v-model="form.users"
      :visible.sync="userSelectVisible"
      @onConfirm="handleUserSelectConfirm"
    />

    <el-dialog
      title="预约时间冲突提醒"
      :visible.sync="conflictDialogVisible"
      width="600px"
    >
      <div
        v-for="(item, index) in conflictRecord.filter(record => record.id !== form.id)"
        :key="index"
        class="conflict-item"
      >
        <p>
          <strong>会议室：</strong>{{ (() => {
            try {
              const roomData = JSON.parse(item.room);
              return roomData.name;
            } catch (e) {
              return '未知会议室';
            }
          })() }}
        </p>
        <p>
          <strong>预约时间：</strong>{{ item.start_time }} ~ {{ item.end_time }}
        </p>
        <p>
          <strong>预约原因：</strong>{{ item.reason }}
        </p>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import WithDialog from '@/components/WithDialog/withDialog.vue'
import { checkReservationTime, getConferenceRoomList, reservationMeetingRoom } from '@/api/conferenceRoom'
import TimeDatePicker from '@/components/TimeDatePicker/TimeDatePicker.vue'
import UserSelectModal from '@/components/UserSelectModal/UserSelectModal.vue'

export default {
  name: 'CreateReserveDialog',
  components: {
    UserSelectModal,
    TimeDatePicker,
    WithDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    defaultRoom: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      form: {
        time: [],
        conference_room_id: null,
        reason: '',
        notes: '',
        users: []
      },
      rules: {
        reason: [
          { required: true, message: '请输入使用原因', trigger: 'blur' }
        ],

        time: [
          {
            required: true,
            type: 'Array',
            validator(rule, value, callback) {
              if (value.length <= 0) {
                callback(new Error('请选择会议时间'))
              } else if (value.length !== 2) {
                callback(new Error('请选择完整的会议时间'))
              } else {
                callback()
              }
            },
            trigger: ['change', 'blur']
          }
        ],

        conference_room_id: [
          {
            validator(rule, value, callback) {
              if (!value) {
                callback(new Error('请选择会议室'))
              } else {
                callback()
              }
            },
            required: true,
            trigger: ['change', 'blur']
          }
        ]
      },
      meetingRoomList: [],
      timePickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 86400000
        }
      },
      userSelectVisible: false,
      selectedUserMap: [],
      conflictDialogVisible: false,
      conflictRecord: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.getRoomList()
        this.$refs?.elFormRef?.resetFields()
      } else {
        this.$refs?.elFormRef?.resetFields()
      }
    },
    defaultRoom(val) {
      if (val) {
        this.form.conference_room_id = val
      }
    }
  },
  methods: {
    handleConfirm() {
      this.$refs.elFormRef.validate(valid => {
        if (valid) {
          if (this.conflictRecord.length) {
            this.conflictDialogVisible = true
            return this.$message.error('当前会议室有预约时间冲突，请修改后提交')
          }
          const { time, conference_room_id, users, notes, reason } = this.form
          const [start_time, end_time] = time
          const data = {
            reason,
            notes,
            users: users.length ? JSON.stringify(users) : null,
            start_time,
            end_time,
            conference_room_id
          }

          this.reservationMeetingRoom(data)
          // this.$emit('confirm', this.form)
        }
      })
    },

    handleCancel() {
      this.$emit('update:visible', false)
    },

    async getRoomList() {
      try {
        const res = await getConferenceRoomList()
        this.meetingRoomList = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '会议室列表获取失败')
      }
    },

    handleOpenUserSelect() {
      this.userSelectVisible = true
    },

    handleUserSelectConfirm(selectIds, selectValMap) {
      console.log('selectValMap --------->', selectValMap)
      this.selectedUserMap = selectValMap
    },

    handleRemove(id) {
      const formUsersIndex = this.form.users.findIndex(item => item === id)
      if (formUsersIndex !== -1) {
        this.form.users.splice(formUsersIndex, 1)
      }

      const selectUsersIndex = this.selectedUserMap.findIndex(item => item.id === id)
      if (selectUsersIndex !== -1) {
        this.selectedUserMap.splice(selectUsersIndex, 1)
        console.log('this.selectedUserMap --------->', this.selectedUserMap)
      }
    },

    async checkTimeConflict() {
      try {
        const { conference_room_id, time } = this.form
        const [start_time, end_time] = time
        const res = await checkReservationTime({ conference_room_id, start_time, end_time })
        this.conflictRecord = []
        this.conflictDialogVisible = false
      } catch (error) {
        this.conflictRecord = error?.response?.data?.data

        if (this.conflictRecord?.length > 0) {
          this.conflictDialogVisible = true
        }
      }
    },

    handleRoomChange() {
      if (this.form.time.length === 2 && this.form.conference_room_id) {
        this.checkTimeConflict()
      }
    },

    handleTimeChange() {
      if (this.form.time.length === 2 && this.form.conference_room_id) {
        this.checkTimeConflict()
      }
    },

    async reservationMeetingRoom(data) {
      this.loading = true
      try {
        const res = await reservationMeetingRoom(data)
        this.$message.success('预约信息提交成功，等待审核')
        this.$emit('update:visible', false)
      } catch (error) {
        this.$message.error('预约信息提交失败')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.selected-warp {
  padding: 10px 10px 0 10px;
  background: #FAFAFA;
  border-radius: 4px;
  border: 1px solid #EBEEF5;

  .base-font {
    color: #303133;
    font-size: 14px;
  }

  .selected-header {
    justify-content: space-between;

    &__title {

    }
  }

  .selected-list {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;

    &__item {
      width: fit-content;
      padding: 8px;
      display: flex;
      justify-content: start;
      align-items: center;
      background-color: #F0F2F5;
      margin-right: 10px;
      margin-bottom: 10px;
      border-radius: 4px;

      .avatar--text {
        width: 38px;
        height: 38px;
        background-color: #1890FF;
        color: #fff;
        border-radius: 4px;
        text-align: center;
        line-height: 38px;
        font-size: 16px;
        flex-shrink:0;
      }

      .name {
        margin-left: 4px !important;
      }

      .icon {
        margin-left: 8px;
        font-size: 18px;
        color: #A8ABB2;
      }

    }
  }

  .conflict-item {
    padding: 15px;
    border-bottom: 1px solid #EBEEF5;
    &:last-child {
      border-bottom: none;
    }
    p {
      margin: 8px 0;
    }
  }
}
</style>
